package controller.DAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import model.Task;

public class DAOTaskSQL implements DAOTask {

	@Override
	public List<Task> getAll() {
		List<Task> all = new ArrayList<Task>();
		Long id;
		String name;

		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet resultSet = null;

		try {
			InitialContext ic = new InitialContext();
			DataSource ds = (DataSource) ic
					.lookup("java:comp/env/jdbc/system_student");
			con = ds.getConnection();
			stmt = con.prepareStatement("SELECT * FROM `tasks`");
			resultSet = stmt.executeQuery();
			while (resultSet.next()) {
				id = resultSet.getLong("id");
				name = resultSet.getString("name");
				all.add(new Task(id, name));
			}
		} catch (SQLException e) {
		} catch (NamingException e) {
			e.printStackTrace();
		} finally {
			try {
				if (resultSet != null)
					resultSet.close();
				if (stmt != null)
					stmt.close();
				if (con != null)
					con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return all;
	}

	@Override
	public Task getTask(Long idTask) {
		Long id = null;
		String name = null;

		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet resultSet = null;

		try {
			InitialContext ic = new InitialContext();
			DataSource ds = (DataSource) ic
					.lookup("java:comp/env/jdbc/system_student");
			con = ds.getConnection();
			stmt = con
					.prepareStatement("SELECT * FROM `tasks` where (`tasks`.`id`=?)");
			stmt.setLong(1, idTask);
			resultSet = stmt.executeQuery();
			resultSet.next();
			if (resultSet != null) {
				id = resultSet.getLong("id");
				name = resultSet.getString("name");
			}

		} catch (SQLException e) {
		} catch (NamingException e) {
			e.printStackTrace();
		} finally {
			try {
				if (resultSet != null)
					resultSet.close();
				if (stmt != null)
					stmt.close();
				if (con != null)
					con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (id != null)
			return new Task(id, name);
		else
			return null;
	}
}
